<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>手把手教你写babel插件 | 七里香</title><meta name="keywords" content="babel"><meta name="author" content="william"><meta name="copyright" content="william"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="先从一个接收了当前babel对象作为参数的 function 开始。 123export default function(babel) &amp;#123;  &#x2F;&#x2F; plugin contents&amp;#125;  由于你将会经常这样使用，所以直接取出 babel.types 会更方便：（译注：这是 ES2015 语法中的对象解构，即 Destructuring） 123export default fun">
<meta property="og:type" content="article">
<meta property="og:title" content="手把手教你写babel插件">
<meta property="og:url" content="http://yokeney.gitee.io/my-hexo-blog/2022/10/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E5%86%99%E4%B8%80%E4%B8%AAbabel/index.html">
<meta property="og:site_name" content="七里香">
<meta property="og:description" content="先从一个接收了当前babel对象作为参数的 function 开始。 123export default function(babel) &amp;#123;  &#x2F;&#x2F; plugin contents&amp;#125;  由于你将会经常这样使用，所以直接取出 babel.types 会更方便：（译注：这是 ES2015 语法中的对象解构，即 Destructuring） 123export default fun">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://yokeney.gitee.io/my-hexo-blog/img/babel.webp">
<meta property="article:published_time" content="2022-10-25T01:10:14.000Z">
<meta property="article:modified_time" content="2023-03-18T02:24:29.487Z">
<meta property="article:author" content="william">
<meta property="article:tag" content="babel">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://yokeney.gitee.io/my-hexo-blog/img/babel.webp"><link rel="shortcut icon" href="/my-hexo-blog/img/index.ico"><link rel="canonical" href="http://yokeney.gitee.io/my-hexo-blog/2022/10/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E5%86%99%E4%B8%80%E4%B8%AAbabel/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/my-hexo-blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/my-hexo-blog/',
  algolia: undefined,
  localSearch: {"path":"/my-hexo-blog/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '手把手教你写babel插件',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2023-03-18 10:24:29'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/my-hexo-blog/img/2.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/my-hexo-blog/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/my-hexo-blog/tags/"><div class="headline">标签</div><div class="length-num">13</div></a><a href="/my-hexo-blog/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/my-hexo-blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 分类</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/vueResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> vue</span></a></li><li><a class="site-page child" href="/my-hexo-blog/reactResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> react</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-shenghuo"></i><span> 后台</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/nodeResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> node</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/my-hexo-blog/img/babel.webp')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/my-hexo-blog/">七里香</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/my-hexo-blog/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 分类</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/vueResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> vue</span></a></li><li><a class="site-page child" href="/my-hexo-blog/reactResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> react</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-shenghuo"></i><span> 后台</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/my-hexo-blog/nodeResources/"><i class="fa-fw iconfont icon-fenlei1"></i><span> node</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">手把手教你写babel插件</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-25T01:10:14.000Z" title="发表于 2022-10-25 09:10:14">2022-10-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-18T02:24:29.487Z" title="更新于 2023-03-18 10:24:29">2023-03-18</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="手把手教你写babel插件"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>先从一个接收了当前<code>babel</code>对象作为参数的 <a target="_blank" rel="noopener" href="https://github.com/babel/babel/tree/master/packages/babel-core"><code>function</code></a> 开始。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span>(<span class="params">babel</span>) &#123;</span><br><span class="line">  <span class="comment">// plugin contents</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于你将会经常这样使用，所以直接取出 <code>babel.types</code> 会更方便：（译注：这是 ES2015 语法中的对象解构，即 Destructuring）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span>(<span class="params">&#123; types: t &#125;</span>) &#123;</span><br><span class="line">  <span class="comment">// plugin contents</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接着返回一个对象，其 <code>visitor</code> 属性是这个插件的主要访问者。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span>(<span class="params">&#123; types: t &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    <span class="attr">visitor</span>: &#123;</span><br><span class="line">      <span class="comment">// visitor contents</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>Visitor 中的每个函数接收2个参数：<code>path</code> 和 <code>state</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span>(<span class="params">&#123; types: t &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    <span class="attr">visitor</span>: &#123;</span><br><span class="line">      <span class="title class_">Identifier</span>(path, state) &#123;&#125;,</span><br><span class="line">      <span class="title class_">ASTNodeTypeHere</span>(path, state) &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>让我们快速编写一个可用的插件来展示一下它是如何工作的。下面是我们的源代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">foo === bar;</span><br></pre></td></tr></table></figure>

<p>其 AST 形式如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">type</span>: <span class="string">&quot;BinaryExpression&quot;</span>,</span><br><span class="line">  <span class="attr">operator</span>: <span class="string">&quot;===&quot;</span>,</span><br><span class="line">  <span class="attr">left</span>: &#123;</span><br><span class="line">    <span class="attr">type</span>: <span class="string">&quot;Identifier&quot;</span>,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;foo&quot;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">right</span>: &#123;</span><br><span class="line">    <span class="attr">type</span>: <span class="string">&quot;Identifier&quot;</span>,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;bar&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们从添加 <code>BinaryExpression</code> 访问者方法开始：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span>(<span class="params">&#123; types: t &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    <span class="attr">visitor</span>: &#123;</span><br><span class="line">      <span class="title class_">BinaryExpression</span>(path) &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们更确切一些，只关注哪些使用了 <code>===</code> 的 <code>BinaryExpression</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">visitor</span>: &#123;</span><br><span class="line">  <span class="title class_">BinaryExpression</span>(path) &#123;</span><br><span class="line">    <span class="keyword">if</span> (path.<span class="property">node</span>.<span class="property">operator</span> !== <span class="string">&quot;===&quot;</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在我们用新的标识符来替换 <code>left</code> 属性：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">BinaryExpression</span>(path) &#123;</span><br><span class="line">  <span class="keyword">if</span> (path.<span class="property">node</span>.<span class="property">operator</span> !== <span class="string">&quot;===&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  path.<span class="property">node</span>.<span class="property">left</span> = t.<span class="title function_">identifier</span>(<span class="string">&quot;sebmck&quot;</span>);</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>于是如果我们运行这个插件我们会得到：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sebmck === bar;</span><br></pre></td></tr></table></figure>

<p>现在只需要替换 <code>right</code> 属性了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">BinaryExpression</span>(path) &#123;</span><br><span class="line">  <span class="keyword">if</span> (path.<span class="property">node</span>.<span class="property">operator</span> !== <span class="string">&quot;===&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  path.<span class="property">node</span>.<span class="property">left</span> = t.<span class="title function_">identifier</span>(<span class="string">&quot;sebmck&quot;</span>);</span><br><span class="line">  path.<span class="property">node</span>.<span class="property">right</span> = t.<span class="title function_">identifier</span>(<span class="string">&quot;dork&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这就是我们的最终结果了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sebmck === dork;</span><br></pre></td></tr></table></figure>



<p>现在我们来手写一个为开发环境<strong>debug</strong>的插件，功能是如果在开发环境下添加debug判断就继续执行条件，到了正式环境自动把debug条件下的逻辑去掉，不用自己手动去删除，达到解放你的双手。</p>
<p>在项目目录下创建index.js,代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="keyword">function</span> (<span class="params">&#123; types: t &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    <span class="attr">visitor</span>: &#123;</span><br><span class="line">      <span class="title class_">Identifier</span>(path) &#123;</span><br><span class="line">        <span class="keyword">const</span> parentNodeIsIfStatement = t.<span class="title function_">isIfStatement</span>(path.<span class="property">parent</span>);</span><br><span class="line">        <span class="keyword">const</span> isDebug = path.<span class="property">node</span>.<span class="property">name</span> === <span class="string">&quot;DEBUG&quot;</span>;</span><br><span class="line">        <span class="keyword">if</span> (isDebug &amp;&amp; parentNodeIsIfStatement) &#123;</span><br><span class="line">          <span class="keyword">const</span> stringNode = t.<span class="title function_">stringLiteral</span>(<span class="string">&quot;DEBUG&quot;</span>);</span><br><span class="line">          path.<span class="title function_">replaceWith</span>(stringNode);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="title class_">StringLiteral</span>(path) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(path.<span class="property">node</span>.<span class="property">value</span>);</span><br><span class="line">        <span class="keyword">const</span> parentNodeIsIfStatement = t.<span class="title function_">isIfStatement</span>(path.<span class="property">parent</span>);</span><br><span class="line">        <span class="keyword">const</span> isDebug = path.<span class="property">node</span>.<span class="property">value</span> === <span class="string">&quot;DEBUG&quot;</span>;</span><br><span class="line">        <span class="keyword">if</span> (isDebug &amp;&amp; parentNodeIsIfStatement) &#123;</span><br><span class="line">          <span class="keyword">if</span> (process.<span class="property">env</span>.<span class="property">NODE_ENV</span> === <span class="string">&quot;production&quot;</span>) &#123;</span><br><span class="line">            path.<span class="property">parentPath</span>.<span class="title function_">remove</span>();</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>然后在项目中创建babel.config.js,我这个是在vue项目中测试的，</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d4d93d06a6dd47c4bcafc2ecd7a6d6a7~tplv-k3u1fbpfcp-watermark.image" alt="截屏2023-03-18 09.40.21.png"></p>
<p>代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">  <span class="attr">presets</span>: [<span class="string">&quot;@vue/cli-plugin-babel/preset&quot;</span>],</span><br><span class="line">  <span class="attr">plugins</span>: [<span class="string">&quot;../index.js&quot;</span>],</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>App.js代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    example</span><br><span class="line">    &lt;button @click=&quot;handleClick&quot;&gt;click&lt;/button&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: &quot;App&quot;,</span><br><span class="line">  setup() &#123;</span><br><span class="line">    const handleClick = () =&gt; &#123;</span><br><span class="line">      console.log(&quot;click&quot;); </span><br><span class="line">      if (DEBUG) &#123;</span><br><span class="line">        console.log(&quot;for debug&quot;)</span><br><span class="line">        const a = 10;</span><br><span class="line">        const b = 20;</span><br><span class="line">        console.log(a + b);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    return &#123;</span><br><span class="line">      handleClick,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br><span class="line">&lt;style&gt;</span><br><span class="line">#app &#123;</span><br><span class="line">  font-family: Avenir, Helvetica, Arial, sans-serif;</span><br><span class="line">  -webkit-font-smoothing: antialiased;</span><br><span class="line">  -moz-osx-font-smoothing: grayscale;</span><br><span class="line">  text-align: center;</span><br><span class="line">  color: #2c3e50;</span><br><span class="line">  margin-top: 60px;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b0a6b93fa0aa441fb6ac1813d4089c6e~tplv-k3u1fbpfcp-watermark.image" alt="截屏2023-03-18 09.51.25.png"></p>
<p>可以看到开发环境下是进入debug判断条件里面的,执行打包之后：</p>
<p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2ebdd31f76c94ad6b1330ecd6bd40285~tplv-k3u1fbpfcp-watermark.image" alt="截屏2023-03-18 10.01.52.png"></p>
<p>完工，是不是很简单😁</p>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/my-hexo-blog/tags/babel/">babel</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/my-hexo-blog/2023/04/24/%E4%B8%8EReact18%E7%9A%84%E5%8C%BA%E5%88%AB%E6%B7%B1%E5%BA%A6%E8%A7%A3%E6%9E%90/"><img class="prev-cover" src="/my-hexo-blog/img/vue_vs-react.png" onerror="onerror=null;src='/my-hexo-blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Vue与React18的区别深度解析</div></div></a></div><div class="next-post pull-right"><a href="/my-hexo-blog/2022/10/15/react%E5%8E%9F%E7%90%86/"><img class="next-cover" src="/my-hexo-blog/img/reactfiber.png" onerror="onerror=null;src='/my-hexo-blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">react原理</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/my-hexo-blog/img/2.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">william</div><div class="author-info__description"> 青山不改，绿水长流</div></div><div class="card-info-data site-data is-center"><a href="/my-hexo-blog/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/my-hexo-blog/tags/"><div class="headline">标签</div><div class="length-num">13</div></a><a href="/my-hexo-blog/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/yokeney"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yokeney" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/my-hexo-blog/965660471@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">加油</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/05/26/VUE3%E9%9B%86%E6%88%90%E4%BC%81%E4%B8%9A%E7%BA%A7%E5%90%8E%E5%8F%B0%E9%80%9A%E7%94%A8%E8%A7%84%E8%8C%83%E6%A8%A1%E7%89%88/" title="VUE3集成企业级后台通用规范模版"><img src="/my-hexo-blog/img/1.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="VUE3集成企业级后台通用规范模版"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/05/26/VUE3%E9%9B%86%E6%88%90%E4%BC%81%E4%B8%9A%E7%BA%A7%E5%90%8E%E5%8F%B0%E9%80%9A%E7%94%A8%E8%A7%84%E8%8C%83%E6%A8%A1%E7%89%88/" title="VUE3集成企业级后台通用规范模版">VUE3集成企业级后台通用规范模版</a><time datetime="2023-05-26T13:17:48.000Z" title="发表于 2023-05-26 21:17:48">2023-05-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/04/24/%E6%B2%A1%E7%9C%8B%E8%BF%99%E7%AF%87%E6%96%87%E7%AB%A0%E4%B9%8B%E5%89%8D%E5%8E%9F%E6%9D%A5%E6%88%91%E5%AF%B9react18%E4%B8%80%E7%9F%A5%E5%8D%8A%E8%A7%A3/" title="没看这篇文章之前原来我对react18一知半解"><img src="/my-hexo-blog/img/react.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="没看这篇文章之前原来我对react18一知半解"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/04/24/%E6%B2%A1%E7%9C%8B%E8%BF%99%E7%AF%87%E6%96%87%E7%AB%A0%E4%B9%8B%E5%89%8D%E5%8E%9F%E6%9D%A5%E6%88%91%E5%AF%B9react18%E4%B8%80%E7%9F%A5%E5%8D%8A%E8%A7%A3/" title="没看这篇文章之前原来我对react18一知半解">没看这篇文章之前原来我对react18一知半解</a><time datetime="2023-04-24T09:11:02.000Z" title="发表于 2023-04-24 17:11:02">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/04/24/%E5%8F%B2%E4%B8%8A%E6%9C%80%E5%85%A8Vue3%E6%80%BB%E7%BB%93/" title="史上最全Vue3总结"><img src="/my-hexo-blog/img/1.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="史上最全Vue3总结"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/04/24/%E5%8F%B2%E4%B8%8A%E6%9C%80%E5%85%A8Vue3%E6%80%BB%E7%BB%93/" title="史上最全Vue3总结">史上最全Vue3总结</a><time datetime="2023-04-24T09:01:19.000Z" title="发表于 2023-04-24 17:01:19">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2023/04/24/%E4%B8%8EReact18%E7%9A%84%E5%8C%BA%E5%88%AB%E6%B7%B1%E5%BA%A6%E8%A7%A3%E6%9E%90/" title="Vue与React18的区别深度解析"><img src="/my-hexo-blog/img/vue_vs-react.png" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="Vue与React18的区别深度解析"/></a><div class="content"><a class="title" href="/my-hexo-blog/2023/04/24/%E4%B8%8EReact18%E7%9A%84%E5%8C%BA%E5%88%AB%E6%B7%B1%E5%BA%A6%E8%A7%A3%E6%9E%90/" title="Vue与React18的区别深度解析">Vue与React18的区别深度解析</a><time datetime="2023-04-24T08:39:32.000Z" title="发表于 2023-04-24 16:39:32">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/my-hexo-blog/2022/10/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E5%86%99%E4%B8%80%E4%B8%AAbabel/" title="手把手教你写babel插件"><img src="/my-hexo-blog/img/babel.webp" onerror="this.onerror=null;this.src='/my-hexo-blog/img/404.jpg'" alt="手把手教你写babel插件"/></a><div class="content"><a class="title" href="/my-hexo-blog/2022/10/25/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%A6%E4%BD%A0%E5%86%99%E4%B8%80%E4%B8%AAbabel/" title="手把手教你写babel插件">手把手教你写babel插件</a><time datetime="2022-10-25T01:10:14.000Z" title="发表于 2022-10-25 09:10:14">2022-10-25</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/my-hexo-blog/img/1.png')"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By william</div><div class="footer_custom_text">关山难越，谁悲失路之人</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/my-hexo-blog/js/utils.js"></script><script src="/my-hexo-blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="/my-hexo-blog/js/search/local-search.js"></script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="22712173" data-server="netease" data-mini="true" data-type="song" data-autoplay="false" data-lrcType="-1"> </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>